package com.example.demo.tools;

import com.example.demo.dao.IdGenerationDao;
import com.example.demo.model.IdGeneration;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
public class CommUtils {

    public static Long createId(Class clazz, int idLength, String datePattern) throws Exception{
        String className = clazz.getName();
        String dateStr = dateFormat(datePattern);
        int ordinalNumber = idLength - dateStr.length();
        long idResult = 0l;
        if (ordinalNumber < 0) {
            throw new Exception("id长度不足，至少要与格式化后的时间长度大出1位，请重新设置！");
        }else {
            IdGenerationDao idGenerationDao = (IdGenerationDao) SpringUtils.getBean("idGenerationDao");
            IdGeneration idGeneration = new IdGeneration();
            idGeneration.setClassName(className);
            idGeneration.setUpdateTime(dateStr);
            List<IdGeneration> idGenerations = idGenerationDao.findByClassNameAndUpdateTime(idGeneration);
            if (idGenerations != null && idGenerations.size() > 0){
                idGeneration = idGenerations.get(0);
                BigDecimal idNum = BigDecimal.valueOf(idGeneration.getIdNum());
                idNum = idNum.add(new BigDecimal(1));
                idResult = idNum.longValue();
                idGeneration.setIdNum(idResult);
                idGenerationDao.update(idGeneration);
                log.info("{}更新id生成策略表， idNum更新为：{}", className, idResult);
            }else {
                idGeneration = new IdGeneration(className, idResult, dateStr);
                idGenerationDao.insert(idGeneration);
                log.info("{}创建id生成策略表， idNum更新为：{}", className, idResult);
            }
            String idResultStr = String.valueOf(idResult);
            while (idResultStr.length() < ordinalNumber) {
                idResultStr = "0" + idResultStr;
            }
            idResultStr = dateStr + idResultStr;
            idResult = Long.parseLong(idResultStr);
            log.info("生成的ID为：{}", idResult);
        }
        return idResult;
    }

    /**
     * 格式化时间
     * @param pattern 格式化时间
     * @return
     */
    public static String dateFormat(String pattern){
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(currentTime);
    }
}
